<!-- 
    裁剪图片
 -->
<template>
    <div class="cropper-avatar">
        <VuePictureCropper
            class="cropper-content"
            :img="img"
            :options="cropperOptions"
            @ready="previewChange"
            @cropend="previewChange"
            @zoom="previewChange"
            :presetMode="{ mode: 'fixedSize', width: 160, height: 160 }"
        >
        </VuePictureCropper>
        <div class="cropper-view">
            <h1>预览</h1>
            <span>
                <img :src="previewImg" alt="预览" />
            </span>
            <span class="preview-circle">
                <img :src="previewImg" alt="预览圆形" />
            </span>
        </div>
    </div>
    <div class="cropper-handler">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">上传</el-button>
    </div>
</template>

<script lang="ts" setup>
import { ref, toRefs } from 'vue'
import VuePictureCropper, { cropper } from 'vue-picture-cropper'
type PropsType = {
    img: string
}

const props = defineProps<PropsType>()
const { img } = toRefs(props)

const cropperOptions = {
    viewMode: 1,
    dragMode: 'move',
    aspectRatio: 1,
    cropBoxResizable: false,
}

// 预览
const previewImg = ref<string>('')
const previewChange = () => {
    const enCode: string = cropper?.getDataURL() as string
    previewImg.value = enCode
}

const emits = defineEmits<{
    (e: 'cancel'): void
    (e: 'confirm', file: File): void
}>()

const cancel = () => {
    emits('cancel')
}

const confirm = async () => {
    const file: File = (await cropper?.getFile()) as File
    emits('confirm', file)
}
</script>

<style lang="less" scoped>
.cropper-avatar {
    height: 400px;
    display: flex;
    .cropper-content {
        flex: 1;
        height: 100%;
    }
    .cropper-view {
        width: 72px;
        padding-left: 30px;
        display: flex;
        flex-direction: column;
        align-items: center;
        > h1 {
            font-size: var(--font-size-large);
        }
        > span {
            .size(72px, 72px);
            display: block;
            margin-top: 15px;
            box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.75);
            img {
                width: 100%;
            }
            &.preview-circle {
                border-radius: 72px;
                overflow: hidden;
            }
        }
    }
}
.cropper-handler {
    margin-top: 15px;
    text-align: center;
}
</style>
